const { stuModel, wechatModel, openedModel, courseModel, workTeaModel } = require('../../model');
const { getResultToObjectComplete } = require('../../services/utils');
const message = require('../message');
const tokens = require('../../services/tokenService');

/**
 * 刷新token
 * @param {Object} object 用户信息
 * @returns {String} Token
 */
const refresh = object => {
  return tokens.createToken({
    id: object.id,
    learn_number: object.learn_number,
    org: object.org,
    name: object.name,
    time: Date.now()
  },24 * 3600 * 15);
};

module.exports = {
  openid_exist: async (req ,res) => {
    const { openid } = req.body;
    try {
      const wechat = await wechatModel.findOne(['id'], {openid: openid});
      if (!wechat) return res.send(message.WECHAT_NEED_BIND);
      const student = await stuModel.findOne(['id', 'learn_number', 'org', 'name'], {id : wechat.id});
      const token = refresh(student);
      return res.send({
        code: 20000,
        token: token
      })
    } catch (e) {
      console.log(e)
    }
  },
  /**
   * 绑定墨猫账号与openid
   */
  bind: async (req, res) => {
    const { openid, learn_number, password } = req.body;

    if (!learn_number || !password) {
      return res.send(message.STU_LOGIN_NULL);}
    if (!openid) {
      return res.send(message.STU_LOGIN_OPENID_NULL);}

    try {
      // TODO 用户密码加密
      const student = await stuModel.findOne([
        'id',
        'learn_number',
        'org',
        'name'
      ], {
        learn_number: learn_number,
        password: password
      });
      if (!student) return res.send(message.STU_LOGIN_FAIL);

      // 查询openid是否存在
      const wechat = await wechatModel.findByFilter(['openid'], { id: student.id });
      const openidExist = wechat.some(item => { if (item.openid === openid) return true });

      if (openidExist) return res.send(message.WECHAT_BIND_REPEAT);
      if (wechat.length < 3) {
        await wechatModel.create({id: student.id, openid: openid, createdAt: Date.now()});
        return res.send({
          ...message.WECHAT_BIND_SUCCESS,
          token: refresh(student)
        });
      } else {
        return res.send(message.WECHAT_BIND_LIMIT);
      }
    } catch (e) { console.error(e) }
  },
  info: (req, res) => {
    const config = {};
    const maxRefreshTime = 24 * 3600 * 7 * 1000; // 1 s = 1000 ms

    tokens.checkToken(req.header('s-token'), function (err,decode) {
      if (err)
        return res.send({code: 50014, message: '身份校验失败'});

      if (Date.now() - decode.time > maxRefreshTime) config.token = refresh(decode);
      config.code = 20000;
      config.data = decode;
      return res.send(config);
    })
  },
};
